// devicecommservice.h
#pragma once

#include <QObject>
#include <QVector>
#include <QVariantMap>
#include <QRegularExpression>
#include <QTimer>
#include <QDateTime>
#include <Common/status_table.h>
#include "DeviceManager/DeviceController.h"

class DeviceCommService : public QObject
{
    Q_OBJECT

public:
    explicit DeviceCommService(QObject* parent = nullptr);
    ~DeviceCommService();

    // 设备通信接口
    Q_INVOKABLE void connectToDevice(const QString& ip = "127.0.0.1", quint16 port = 9600);
    Q_INVOKABLE void disconnectFromDevice();
    Q_INVOKABLE void setCommands(const QVector<QString> &commands);
    Q_INVOKABLE void setCommandGroups(const QVector<QVector<QString>> &commandGroups);
    Q_INVOKABLE void uploadAllCommands();
    Q_INVOKABLE void stopExecution();
    Q_INVOKABLE void startExecute();
    Q_INVOKABLE void clearAction();    //清除指令和初始化指令
    // 动作指令
    Q_INVOKABLE void DeviceCommand(DeviceProtocol::IPCCommand command,
                                   const QVariantMap &params = QVariantMap());

    Q_INVOKABLE void RegressionAction();
    Q_INVOKABLE void executeCommandsProcessing();

    Q_INVOKABLE void setupRecipeParams(double toolDiameter, double toolSpeed,
                                       double lineSpacing, double cuttingDepth, double feedRate);

    // 全自动执行方法
    Q_INVOKABLE void executeAllGroupsAutomatically();
    Q_INVOKABLE bool isAutoExecuting() const { return m_autoMode; }
    Q_INVOKABLE void stopAutoExecution();
    Q_INVOKABLE bool hasMoreGroups() const;

    // 状态查询接口
    Q_INVOKABLE void queryDeviceState();
    Q_INVOKABLE void queryRecipeParams();
    Q_INVOKABLE void queryDIStatus();
    Q_INVOKABLE void getCurrentStatus(StatusTable& status) const;
    Q_INVOKABLE bool isConnected() const { return m_connected; }
    Q_INVOKABLE QString getConnectionStatus() const;

    // 数据获取
    QVector<QString> getRemainingCommands() const { return m_commands; }

signals:
    void deviceConnected();
    void deviceDisconnected();
    void deviceErrorOccurred(const QString& errorMessage);
    void commandExecuted(const QString& command, bool success);
    void logMessage(const QString& message);
    void statusUpdated(const StatusTable& status);

    // 全自动执行信号
    void autoExecutionStarted();
    void autoExecutionProgress(int currentGroup, int totalGroups, const QString& status);
    void autoExecutionStopped();

    // 分组执行信号
    void groupUploaded(int groupIndex, int commandCount);
    void groupExecutionFinished(int groupIndex);
    void allGroupsExecutionFinished();

    // 新增自动执行完成信号
    void autoExecutionFinished(bool success, const QString& message);

private slots:
    void onDeviceConnected();
    void onDeviceDisconnected();
    void onDeviceErrorOccurred(const QString& error);
    void onCommandResponseReceived(DeviceProtocol::IPCCommand command, bool success, const QString& message);
    void onCommandDataResponseReceived(DeviceProtocol::IPCCommand command, bool success, const QVariantMap& data);
    void onQueryDataReceived(DeviceProtocol::IPCCommand command, const QVariantMap &data); // 立即查询数据槽
    void onAutoConnectTimeout();
    void onGroupExecutionFinished();

private:
    void setupConnections();
    void autoConnectToDevice();
    void parseCommandParams(const QString& command);
    void clearAndUploadGroup();
    void uploadNextGroupAuto();
    void startGroupExecutionAuto();
    void checkGroupExecutionStatus();
    void startGroupExecutionMonitoring();
    void stopGroupExecutionMonitoring();

    // 新增执行状态监控函数
    void handleExecutionStateChange(RunStatus oldStatus, RunStatus newStatus);
    void checkForQuickExecution();
    QString getRunStatusText(RunStatus status);

    int getCN(const QString& command);
    QVariantMap getMotionParams(const QString& command);

    void log(const QString& message);
    void handleQueryData(DeviceProtocol::IPCCommand command, const QVariantMap& data);
    void updateDeviceStatus(const QVariantMap& stateData);
    void updateRecipeParams(const QVariantMap& recipeData);
    void updateDIStatus(const QVariantMap& diData);
    void updateConnectionStatus(bool connected);
public:
    QVariantMap getIoBits(const QString& command);

private:
    DeviceController* m_deviceController;
    bool m_connected;
    QVector<QString> m_commands;
    QVector<QVector<QString>> m_commandGroups;
    int m_currentGroupIndex;
    int m_totalGroups;
    bool m_autoMode;
    bool m_isGroupExecuting;
    QTimer* m_autoConnectTimer;
    QTimer* m_executionMonitorTimer;
    StatusTable m_statusTable;
    int m_currentCommandIndex;

    // 新增执行监控相关成员变量
    QDateTime m_executionStartTime;
    int m_timeoutCount = 0;
    static const int MAX_TIMEOUT_CHECKS = 3600; //  1小时超时 (3600 * 1秒)
    static const int CYLINDER_TIMEOUT_CHECKS = 2; // 气缸组2秒超时
public:
    enum GroupType {
        MotionGroup,    // 移动组
        CylinderGroup   // 气缸组
    };
    GroupType getCurrentGroupType(const QVector<QString>& commands);
    void checkMotionGroupCompletion();
    bool checkCylinderGroupCompletion();
    bool isQuickMotionGroup(int groupIndex);
private:
    GroupType m_currentGroupType; // 当前组类型
    QString m_initialFixtureStatus; // 初始气缸状态
};
